package com.pig4cloud.pigx.admin.controller;

import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @Author 兔子不吃窝边曹
 * @create 2022/8/5 14:22
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/token")
public class PigxTokenController {

    /**
     * 用户信息
     */
    @GetMapping("/info")
    public R logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) {
            log.info("用户没有通过验证");
        }
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof User) {
            username = ((User) principal).getUsername();
        } else {
            username = principal.toString();
        }
        log.info("用户名:{}", username);
        return R.ok(username);
    }

    /**
     * 获取用户
     */
    @GetMapping("/userInfo")
    public R getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) {
            log.info("用户没有通过验证");
        }
        Object principal = authentication.getPrincipal();
        PigxUser pigxUser = null;
        if (principal instanceof PigxUser) {
            pigxUser = (PigxUser) principal;
        }
        return R.ok(pigxUser);
    }

}
